#include <math.h>

short beatval;

#define SCALING 256

#define SAMPLERATE 32000
#define SAMPLESIZE 1024

#define LOCAL_VAL (SAMPLERATE/SAMPLESIZE)

#if(LOCAL_VAL < 8)
#warning Thats a strange samplesize and samplerate
#endif

signed char samples[SAMPLESIZE];
int sampindex = 0;
long sampval = 0;

signed short energies[LOCAL_VAL];
int energyindex = 0;
long energyval = 0;

short beatvalue(void)
{
	return beatval;
}

void beatfilter(signed char value)
{
	//Sample "instant" sum of squares
	sampval = sampval + value*value - samples[sampindex]*samples[sampindex];
	samples[sampindex++] = value;
	if(sampindex >= SAMPLESIZE)
		sampindex = 0;
	
	//Calc short term energy values
	energyval = energyval + (sampval*SCALING)/LOCAL_VAL - energies[energyindex];
	
	//Variance step. Heavy shit
	long val = 0;
	for(int i = 0; i<LOCAL_VAL; i++)
	{
		long v = (energies[i]-energyval);
		val += v*v;
	}
	val /= LOCAL_VAL;
	
	short c = ceil((((float)val)*-0.0025714)+1.5142857);
	energies[energyindex++] = c;
	if(energyindex >= LOCAL_VAL)
		energyindex = 0;
	
	short omg = c*energyval;
	if(sampval > omg)
		beatval = sampval-omg;
	else
		beatval = 0;
}
